#ifndef TCP_SERVER_H
#define TCP_SERVER_H

#include <QTcpServer>
#include "tcp_socket.h"

class TcpServer : public QTcpServer
{
    Q_OBJECT
public:
    explicit TcpServer(QObject *parent = 0);
    ~TcpServer();

protected:
    void incomingConnection(qintptr handle);

private:
    QList<TcpSocket *> clients;

    //socketDescriptor唯一标识
    /**
     * @brief handleChatHash
     *        记录TCP对应的业务类实例
     */
    QHash<qintptr, TcpSocket*> m_handleTcpClientHash;
    /**
     * @brief handleThreadHash
     *        记录TCP对应的子线程
     */
    QHash<qintptr,QThread*> m_handleThreadHash;


signals:
    /**
     * @brief sendClientData：向主界面传递发送的数据
     * @param ip
     * @param port
     * @param data
     */
    void sendClientData(const QString &ip, int port, QByteArray data);
    /**
     * @brief sendClientData：向主界面传递接受的数据
     * @param ip
     * @param port
     * @param data
     */
    void receiveData(const QString &ip, int port, QByteArray data);
    /**
     * @brief sendClientData：向主界面传递客户端连接的状态
     * @param ip
     * @param port
     * @param data
     */
    void clientConnected(const QString &ip, int port);
    /**
     * @brief sendClientData：向主界面传递客户端断联的状态
     * @param ip
     * @param port
     * @param data
     */
    void clientDisconnected(const QString &ip, int port);

    /**
     * @brief 发送数据
     * @param data
     */
    void sendSocketData(const QString &ip, int port, const QByteArray data);

    /**
     * @brief 传递设备状态
     */
    void conveyEquipmentStatusType(int);

    void startInitializeTcpSocketFunction();


public slots:
    //启动服务
    bool start(QString ip, int port);
    //停止服务
    void stop();

    //关闭服务器
    void closeServer();

    //指定连接发送数据
    void writeData(const QString &ip, int port, QByteArray data);
    //对所有连接发送数据
    void writeData(QByteArray data);

    //断开指定连接
    void remove(const QString &ip, int port);
    //断开所有连接
    void remove();

    //关闭全部客户端线程
    void closeClientAllThread();
    //关闭单个客户端线程
    void closeClientOneThread(qintptr socketDescriptor);

    //关闭全部套接字
    void closeAllSocket();
    //关闭单个套接字
    void closeOneSocket(const QString &ip, int port);

private slots:
    /**
     * @brief 断开连接
     * @param socketDescriptor
     */
    void disconnected(qintptr socketDescriptor);

};


#endif // TCP_SERVER_H
